package com.ruoyi.system.amqp;

import com.alibaba.fastjson2.JSONObject;
import com.ruoyi.system.amqp.taskscheduler.RedisCacheUpdateTask;
import com.ruoyi.system.domain.LineDevice;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import javax.annotation.PostConstruct;
import javax.jms.Message;

import com.ruoyi.system.service.ILineDeviceService;

import java.nio.charset.StandardCharsets;
import java.util.List;
import java.util.Objects;

@Component
public class AmqpMessageSub{

    Integer count = -1;

    @Autowired
    ILineDeviceService iLineDeviceService;

    @Autowired
    ProductMatcher productMatcher;

    @Autowired
    RedisCacheUpdateTask redisCacheUpdateTask;

    private final static Logger logger = LoggerFactory.getLogger(AmqpMessageSub.class);

    private String topic;
    private String messageId;
    private Long generateTime;
    private String content;

    private int productType;

    public String getTopic() {
        return topic;
    }

    public void setTopic(String topic) {
        this.topic = topic;
    }

    public String getMessageId() {
        return messageId;
    }

    public void setMessageId(String messageId) {
        this.messageId = messageId;
    }

    public Long getGenerateTime() {
        return generateTime;
    }

    public void setGenerateTime(Long generateTime) {
        this.generateTime = generateTime;
    }

    public String getContent() {
        return content;
    }

    public void setContent(String content) {
        this.content = content;
    }

    public int getProductType() {
        return productType;
    }

    public void setProductType(int productType) {
        this.productType = productType;
    }


    public AmqpMessageSub() {
    }

    public void processMessage(Message message) {

        try {
            byte[] body = message.getBody(byte[].class);
            String content = new String(body, StandardCharsets.UTF_8);
            String topic = message.getStringProperty("topic");
            String messageId = message.getStringProperty("messageId");
            long generateTime = message.getLongProperty("generateTime");
//            logger.info("receive message"
//                    + ",\n topic = " + topic
//                    + ",\n messageId = " + messageId
//                    + ",\n generateTime = " + generateTime
//                    + ",\n content = " + content);
            JSONObject jsonObject = JSONObject.parseObject(content);
            String productKey = jsonObject.getString("productKey");
            String deviceName = jsonObject.getString("deviceName");
            int productType = productMatcher.getTopicType(topic);
            LineDevice lineDevice = new LineDevice();
            if(!topic.matches(".*/as/mqtt/status.*")){ // 物模型数据!!!
                //写数据库
                String data = jsonObject.getJSONObject("items").toJSONString();
                lineDevice.setName(deviceName); //不能少！！！
                lineDevice.setStatus(1);
                lineDevice.setDelFlag(0);
                lineDevice.setData(data);
                iLineDeviceService.updateLineDevice(lineDevice);
                //写redis缓存
//                if(count % 3 == 0){
//                    redisCacheUpdateTask.setRedisCache(deviceName);
//                }
                count++;
            }
            else {
                String status = jsonObject.getString("status");
                LineDevice queryDevice = new LineDevice();
                queryDevice.setName(deviceName);
                List<LineDevice> list = iLineDeviceService.selectLineDeviceList(queryDevice);
                //查找该设备是否已经存在
                if(list.size()>0){
                    lineDevice = list.get(0);
                    lineDevice.setName(deviceName);
                    lineDevice.setStatus(Objects.equals(status, "online") ?1:0);
                    iLineDeviceService.updateLineDevice(lineDevice);
                }else{
                    lineDevice = new LineDevice();
                    lineDevice.setName(deviceName);
                    lineDevice.setCustomName(deviceName);
                    lineDevice.setStatus(Objects.equals(status, "online") ?1:0);
                    lineDevice.setType(productMatcher.getTopicType(productKey));
                    iLineDeviceService.insertLineDevice(lineDevice);
                }
            }
            if (count % 100 == 99) {
                count = 0;
            } else if (count == -1) {
                redisCacheUpdateTask.deleteAllDevicesRedisCache();
                count = 0;
            }
        } catch (Exception e) {
            logger.error("processMessage occurs error ", e);
        }
    }
}
